#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>

#define MAX_PORTS 65535

int main() {
    int sockfd;
    struct sockaddr_in server;
    struct hostent *host;
    struct sockaddr_in local;
    socklen_t addrlen = sizeof(local);

    // 创建套接字
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1) {
        perror("socket");
        exit(EXIT_FAILURE);
    }

    // 获取本地主机名
    char hostname[256];
    gethostname(hostname, sizeof(hostname));

    // 获取本地主机信息
    host = gethostbyname(hostname);
    if (host == NULL) {
        perror("gethostbyname");
        exit(EXIT_FAILURE);
    }

    // 设置服务器地址结构
    server.sin_family = AF_INET;
    server.sin_addr = *((struct in_addr *)host->h_addr);
    memset(&(server.sin_zero), 0, 8);

    printf("Proto\tLocal Address\t\tForeign Address\t\tState\n");

    // 检查每个端口的状态
    for (int port = 1; port <= MAX_PORTS; ++port) {
        // 设置端口号
        server.sin_port = htons(port);

        // 尝试连接到端口
        if (connect(sockfd, (struct sockaddr *)&server, sizeof(server)) == 0) {
            if (getsockname(sockfd, (struct sockaddr *)&local, &addrlen) == -1) {
                perror("getsockname");
                exit(EXIT_FAILURE);
            }

            char localAddress[INET_ADDRSTRLEN];
            char foreignAddress[INET_ADDRSTRLEN];
            inet_ntop(AF_INET, &(local.sin_addr), localAddress, INET_ADDRSTRLEN);
            inet_ntop(AF_INET, &(server.sin_addr), foreignAddress, INET_ADDRSTRLEN);

            printf("TCP\t%s:%d\t\t%s:%d\t\tESTABLISHED\n", localAddress, ntohs(local.sin_port), foreignAddress, port);
        }
        else
        {
            printf("connect failed");
        }

        close(sockfd);
    }

    return 0;
}